package uuid

import (
	"encoding/binary"
	"gomicrodemo/common/uuid/snowflake"
	"net"
	"os"
	"sync"

)

var (
	node *snowflake.Node
	once sync.Once
)

//待补充注释
func GetUUID() int64 {
	once.Do(func() {
		nodeId := getNodeId()
		node = snowflake.NewNode(nodeId)
	})

	return node.Generate().Int64()
}

// 获取snowflake的节点ID
func getNodeId() int64 {

	// 尝试取mac，注意nodeid为10bit，正整数
	if ifaces, err := net.Interfaces(); err == nil {
		for _, iface := range ifaces {
			if iface.HardwareAddr != nil {
				macInt := binary.BigEndian.Uint32(iface.HardwareAddr)
				return int64(macInt & 0x3FF) // 取 10 bit
			}
		}
	}

	// 若 mac 取失败，则使用pid兜底
	return int64(os.Getpid())
}
